import Axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { message } from "antd";
import { getToken, removeToken } from "./token";
export interface Response<T = any> {
    code: number;
    data: T;
    message: string;
}
const axios = Axios.create({
    baseURL: "/api",
});
axios.interceptors.request.use(config => {
    const token = getToken();
    token && ((config.headers as any)["Authorization"] = "Bearer " + token);
    return config;
});
let flag = false;
axios.interceptors.response.use(
    response => {
        const data = response.data as Response;
        if (data.code === 400) {
            message.error(data.message);
            return Promise.reject(data);
        }
        if (data.code === 500) {
            message.error(data.message);
            return Promise.reject(data);
        }
        return response.data;
    },
    err => {
        const { response } = err;
        console.log(response);
        if (response.status === 401) {
            if (flag) {
                return;
            }
            flag = true;
            message.error(response.data.message ?? "登录失效即将跳转到登录");
            removeToken();
            setTimeout(() => {
                location.href = "/login";
            }, 1000);
        } else {
            message.error("系统异常请联系管理员");
        }
    }
);
class Request {
    static create(): RequestInstance {
        const request = function (url: string, config?: AxiosRequestConfig) {
            return arguments.length === 1 ? axios(url) : axios(url, config);
        };
        const keys = Object.getOwnPropertyNames(Request.prototype);
        for (let i = 1; i < keys.length; i++) {
            const key = keys[i];
            (request as any)[key] = (Request.prototype as any)[key];
        }
        return request as RequestInstance;
    }
    get<T, R = Response<T>>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<R> {
        return axios.get<any, R>(url, config);
    }
    post<T, R = Response<T>>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<R> {
        return axios.post<any, R>(url, data, config);
    }
    delete<T, R = Response<T>>(
        url: string,
        config?: AxiosRequestConfig
    ): Promise<R> {
        return axios.delete<any, R>(url, config);
    }
    put<T, R = Response<T>>(
        url: string,
        data?: any,
        config?: AxiosRequestConfig
    ): Promise<R> {
        return axios.put<any, R>(url, data, config);
    }
}
interface RequestInstance extends Request {
    <T, R = Response<T>>(config: AxiosRequestConfig): Promise<R>;
    <T, R = Response<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
}
const request = Request.create();
export default request;
